package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private static final String APPID = "appid";
    private static final String APP_SECRET = "secret";
    private static final String Grant_Type = "grant_type";
    private static final String Js_Code = "js_code";
    private static final String WeChat_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) throws JsonProcessingException {

        String openid = getOpenId(userLoginDTO);
        log.info("openid:{}", openid);
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid == null) {
            throw new UserNotLoginException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 判断当前用户是否为新用户
        User user = userMapper.selectUserByOpenId(openid);
        if (user == null) {
            // 如果是新用户，自动完成注册.通过openid获取用户一系列信息
            User newUser = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();

            userMapper.addUser(newUser);
            return newUser;
        }
        // 返回这个用户对象
        return user;
    }

    public String getOpenId(UserLoginDTO userLoginDTO) {
        //1.发给微信服务器请求，获取openid，
        Map<String, String> params = new HashMap<>();
        params.put(APPID, weChatProperties.getAppid());
        params.put(APP_SECRET, weChatProperties.getSecret());
        params.put(Grant_Type, "authorization_code");
        params.put(Js_Code, userLoginDTO.getCode());
        String json = HttpClientUtil.doGet(WeChat_URL, params);
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}
